package la.iok.hzsvn.lewin.movie.service;

import la.iok.hzsvn.lewin.movie.config.DfsProperties;
import la.iok.hzsvn.lewin.movie.core.exception.ErrorCode;
import la.iok.hzsvn.lewin.movie.entity.ClueCard;
import la.iok.hzsvn.lewin.movie.entity.ClueCardFile;
import la.iok.hzsvn.lewin.movie.entity.ClueCardInstance;
import la.iok.hzsvn.lewin.movie.mapper.ClueCardFileMapper;
import la.iok.hzsvn.share.annotations.NotNull;
import la.iok.hzsvn.share.annotations.Nullable;
import la.iok.hzsvn.share.dfs.model.DfsDescriptor;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;

@Service
public class ClueCardFileServiceImpl extends MovieFileServiceImpl<ClueCardFile, ClueCardFileMapper> implements ClueCardFileService{
    public ClueCardFileServiceImpl(ClueCardFileMapper mapper, WebDfsService webDfsService, DfsProperties dfsProperties) {
        super(mapper, webDfsService, dfsProperties);
    }

    @Override
    public void downloadFile(@NotNull HttpServletResponse response, @Nullable Long fileId, @NotNull String clueCardName) {
        ClueCardFile file = select(fileId);
        ErrorCode.CLUE_CARD_FILE_NOT_EXIST.assertNotNull(file,clueCardName);
        DfsDescriptor descriptor = webDfsService.dfsFile(file.getPath());
        ErrorCode.CLUE_CARD_FILE_NOT_EXIST.assertTrue(webDfsService.exist(descriptor),clueCardName);
        webDfsService.downloadFile(response,descriptor,file.getFileName());
    }

    @Override
    protected void validateReference(@NotNull ClueCardFile file) {
        ClueCardInstance item = executeSelect(ClueCardInstance.class,"select * from "
                + ClueCardInstance.class.getSimpleName() + " where fileDeleted=0 and (sdFileId=" + file.getId() + " or hdFileId=" + file.getId() + ") limit 1");
        ErrorCode.FILE_REFERENCED_BY_OTHER.assertNull(item,file.getPath(),ClueCardInstance.class.getSimpleName());

        ClueCard item2 = executeSelect(ClueCard.class,"select * from "
                + ClueCard.class.getSimpleName() + " where sdFileId=" + file.getId() + " or hdFileId=" + file.getId() + " limit 1");
        ErrorCode.FILE_REFERENCED_BY_OTHER.assertNull(item2,file.getPath(),ClueCard.class.getSimpleName());
    }
}
